# author： Zichen
# date: 2021-04-03
# instruction：发送文件至自己的邮箱
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog

import Mainwindow  # 填写导入的py文件名
import MailSent
import configparser
version = '0.1.1.210404_alpha'
#  实例化configParser对象
config = configparser.ConfigParser()


def Get_fileConfigPath():
    try:
        # 获取配置文件路径
        fileConfigPathtemp = QFileDialog.getOpenFileName()
        # 在文本框内显示
        ui.fileConfig.setPlainText(fileConfigPathtemp[0])
        # 选择完配置文件显示接收者至下拉项进行选择
        config.read(ui.fileConfig.toPlainText(), encoding='utf-8')
        ui.SelectToaddrs.addItems(list(config['toaddrs']))
        # 显示信息
        ui.display.append('已导入配置文件√')
    except:
        ui.display.append('[ERROR]导入配置文件错误×')


def Get_fileAttachmentsPath():
    try:
        # 获取多个附件路径(列表)
        fileAttachmentsPathtemp = QFileDialog.getOpenFileNames()
        fileAttachmentsPathlst = fileAttachmentsPathtemp[0]
        # 将数据进行拼接变为字符串并显示在文本框中便于发送时获取
        ui.filePath.setPlainText(';'.join(str(i)
                                          for i in fileAttachmentsPathlst))
        ui.display.append('已导入附件路径√')
    except:
        ui.display.append('[ERROR]导入附件路径错误×')


def SendDataProcessing():
    # 发送前数据处理
    # try:
    Mail = MailSent.MailSent()

    # 显示发送功能版本号
    ui.display.append('\n已导入插件%s\n版本号 :%s\n' % (Mail.Name, Mail.vision))

    message_subject = ui.message_subject.toPlainText()
    message = ui.message.toPlainText()
    if ui.filePath.toPlainText() != 'None':
        filePath = ui.filePath.toPlainText().split(';')
    else:
        filePath = 'None'

    # -read读取.conf文件
    config.read(ui.fileConfig.toPlainText(), encoding='utf-8')
    fromaddr = config['Account']['Senderaddr']
    password = config['Account']['password']
    toaddrs = [config['toaddrs']['%s' % ui.SelectToaddrs.currentText()]]
    HOST = config['Mail']['HOST']
    PORT = config['Mail']['PORT']
    Mail.Send(fromaddr, toaddrs, password,
              message_subject, message, filePath, HOST, PORT)
    ui.display.append('已发送邮件√')
    # except:
    # ui.display.append('[ERROR]发送错误×')


if __name__ == '__main__':
    app = QApplication(sys.argv)
    MainWindow = QMainWindow()
    ui = Mainwindow.Ui_MainWindow()  # 填写导入的py文件名以及内部类名
    ui.setupUi(MainWindow)
    MainWindow.setWindowTitle(vision)  # 将窗口标题设置为版本号
    MainWindow.show()

    # 配置文件路径获取
    ui.Select_fileConfig.clicked.connect(Get_fileConfigPath)
    # 附件路径获取
    ui.AddAttachments.clicked.connect(Get_fileAttachmentsPath)
    # 发送
    ui.Send.clicked.connect(SendDataProcessing)
    sys.exit(app.exec_())
